<?php

/** 邀请活动页面*/

namespace App\Http\Controllers\Api;

use App\Enums\AvailableStatus;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\FrontendUser;
use App\Models\InvitationActivity;
use App\Models\InvitationRegister;

class InvitationActivityController extends Controller
{
    /*邀请注册页面-活动列表*/
    public function listInviteActivites()
    {
        $page = request()->page ?: 1;
        $limit = request()->limit ?: 10;

        $query = InvitationActivity::query()
            ->where('status', AvailableStatus::ENABLED)
            ->where('agent_id', request()->agent_id)
            ->orderByDesc('start_time');

        $count = $query->count();

        $list = $query->offset(($page - 1) * $limit)->limit($limit)
            ->get()->map(function (InvitationActivity $item) {
                return [
                    'id' => $item->id,
                    'name' => $item->name,
                    'img_url' => $item->img_url,
                    'start_time' => $item->start_time,
                    'end_time' => $item->end_time,
                    'ongoing_status' => $item->getOnGoingStatus()->value,
                ];
            });

        return [
            'list' => $list,
            'count' => $count,
        ];
    }

    /*活动详情*/
    public function findInviteActivity($id)
    {
        $activity = $this->findActivityOrFail($id);

        return [
            'name' => $activity->name,
            'img_url' => $activity->img_url,
            'start_time' => $activity->start_time,
            'end_time' => $activity->end_time,
            'ongoing_status' => $activity->getOngoingStatus()->value,
        ];
    }

    /*单个活动排名*/
    public function listInviteRankings($id)
    {
        $page = request()->page ?: 1;
        $limit = request()->limit ?: 10;

        /** @var InvitationActivity $activity */
        $activity = $this->findActivityOrFail($id);
        $query = InvitationRegister::query()
            ->with(['user'])
            ->where('activity_id', $id)
            ->where('is_allowed', AvailableStatus::ENABLED)
            ->where('realname_count', '>', 0)
            ->limit($activity->ranking_num);

        $count = $query->count();
        $registers = $query
            ->orderByDesc('realname_count')
            ->orderByDesc('id')
            ->get();

        /** @var FrontendUser $user */
        $user = auth()->user();
        $list = $myRanking = [];
        foreach ($registers as $index => $register) {
            $list[] = [
                'mobile' => hide_mobile($register->user->mobile),
                'invite_id' => $register->invite_id,
                'register_num' => $register->register_count,
                'realname_num' => $register->realname_count,
            ];
            if ($register->invite_id === $user->id) {
                $myRanking = [
                    'ranking' => $index + 1,
                    'register_num' => $register->register_count,
                    'realname_num' => $register->realname_count,
                ];
            }
        }
        if (empty($myRanking)) {
            //我的排名数据
            $me = InvitationRegister::query()
                ->where('activity_id', $id)
                ->where('is_allowed', AvailableStatus::ENABLED)
                ->where('invite_id', auth()->id())
                ->first();
            if ($me) {
                $myRanking = [
                    'ranking' => '',
                    'register_num' => $me->register_count,
                    'realname_num' => $me->realname_count,
                ];
            }
        }
        //最近更新时间
        if (now() > $activity->end_time) {
            $lastUpdateTime = date('Y/m/d H:i:s', strtotime($activity->end_time));
        } else {
            $lastUpdateTime = date('Y/m/d H:i:s', time());
        }

        return [
            'list' => array_slice($list, ($page - 1) * $limit, $limit),
            'count' => $count,
            'my_ranking' => $myRanking,
            'last_update_time' => $lastUpdateTime,
        ];
    }

    /*单条活动我的邀请-全部*/
    public function listMyInvite($id)
    {
        $page = request()->page ?: 1;
        $limit = request()->limit ?: 10;

        $user = auth()->user();
        $userId = $user->id;
        /** @var InvitationActivity $activity */
        $activity = $this->findActivityOrFail($id);
        $query = FrontendUser::query()
            ->with(['auth', 'paid_order'])
            ->where('parent_id', $userId)
            ->where('created_at', '>=', $activity->start_time)
            ->where('created_at', '<=', $activity->end_time)
            ->when(request()->is_real && !$activity->enable_consume, function ($q) {
                $q->whereHas('auth');
            })
            ->when(request()->is_real && $activity->enable_consume, function ($q) {
                $q->whereHas('paid_order');
            });

        $count = $query->count();
        $list = $query->orderByDesc('id')
            ->limit($limit)->skip(($page - 1) * $limit)
            ->get()
            ->map(function (FrontendUser $user) use ($activity) {
                return [
                    'mobile' => hide_mobile($user->mobile),
                    'create_time' => $user->created_at->toDateTimeString(),
                    'is_real' => (bool) ($activity->enable_consume ? $user->paid_order->count() : $user->auth),
                ];
            });

        return [
            'list' => $list,
            'count' => $count,
            'enable_consume' => (bool) $activity->enable_consume,
        ];
    }

    /*查询邀请活动*/
    private function findActivityOrFail($id)
    {
        $activity = InvitationActivity::query()
            ->where('agent_id', request()->agent_id)
            ->where('id', $id)
            ->first();
        if (!$activity) {
            throw new ApiException('活动未找到');
        }

        return $activity;
    }
}
